package com.rency.mtds.manager.repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rency.mtds.manager.dal.dao.DataSourceDao;
import com.rency.mtds.manager.dal.entity.DataSourcePO;
import org.rency.halo.framework.lang.enums.YesNo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: caiyu.ren
 * Created on 2019/10/11 9:08
 * @version: V1.0.0
 * @since JDK 11
 */
@Repository
public class DataSourceRepository {

    @Autowired
    private DataSourceDao dataSourceDao;

    public DataSourcePO load(Long id){
        QueryWrapper<DataSourcePO> wrapper = new QueryWrapper<>();
        wrapper.eq("ID",id);
        return dataSourceDao.selectOne(wrapper);
    }

    public List<DataSourcePO> loadAll(){
        QueryWrapper<DataSourcePO> wrapper = new QueryWrapper<>();
        wrapper.eq("ENABLE",YesNo.YES.getCode());
        return dataSourceDao.selectList(wrapper);
    }

    public List<DataSourcePO> find(String appId){
        QueryWrapper<DataSourcePO> wrapper = new QueryWrapper<>();
        wrapper.eq("APP_ID",appId);
        wrapper.eq("ENABLE",YesNo.YES.getCode());
        return dataSourceDao.selectList(wrapper);
    }

    public boolean store(DataSourcePO entity){
        return dataSourceDao.insert(entity) == 1;
    }

    public boolean updateEnable(Long id, YesNo newEnable, YesNo oldEnable){
        UpdateWrapper<DataSourcePO> wrapper = new UpdateWrapper<>();
        wrapper.eq("ID",id);
        wrapper.eq("ENABLE",oldEnable.getCode());

        DataSourcePO entity = new DataSourcePO();
        entity.setEnable(newEnable.getCode());
        entity.setGmtModified(LocalDateTime.now());

        return dataSourceDao.update(entity,wrapper) == 1;
    }

}
